package com.gzyj.server.nettyserver.handler;

import com.gzyj.jtt808.utils.HexBytesUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author lhj
 */

public class ProtocolDecoder extends ByteToMessageDecoder {

    private Logger logger = LoggerFactory.getLogger("commondLog");


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in == null) {
            return;
        }
        String hex = ByteBufUtil.hexDump(in);
        in.markReaderIndex();
        ByteBuf byteBuf = in.asReadOnly();
        byteBuf.markReaderIndex();
        while (in.isReadable()) {
            in.markReaderIndex();
            int packetBeginIndex = in.readerIndex();
            byte tag = in.readByte();
            // 搜索包的开始位置
            // 处理黏包和拆包
            if (tag == 0x7E) {
                if (!in.isReadable()) {
                    in.resetReaderIndex();
                    return;
                } else {
                    tag = in.readByte();
                    // 防止是两个0x7E,取后面的为包的开始位置
                    // 寻找包的结束
                    while (tag != 0x7E) {
                        if (in.isReadable() == false) {
                            in.resetReaderIndex(); // 没有找到结束包，等待下一次包
                            return;
                        }
                        tag = in.readByte();
                    }
                    int pos = in.readerIndex();
                    int packetLength = pos - packetBeginIndex;
                    if (packetLength > 2) {
                        byte[] tmp = new byte[packetLength];
                        in.resetReaderIndex();
                        in.readBytes(tmp);
                        out.add(Unpooled.copiedBuffer(tmp));
                        logger.info("收到数据" + HexBytesUtil.bytesToHex(tmp));

                    } else {
                        // 说明是两个0x7E
                        logger.error("收到2个7E，Index:" + in.readerIndex() + " 长度 = " + packetLength + " 末尾数据 = " + HexBytesUtil.bytesToHex(new byte[]{tag}));
                        in.resetReaderIndex();
                        in.readByte(); // 两个7E说明前面是包尾，后面是包头
                    }
                }
            } else if (in.isReadable() && byteBuf.isReadable()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                if (hex.startsWith("30316364")) {
                    out.add(Unpooled.copiedBuffer(bytes));
                } else {
                    byteBuf.readBytes(bytes);
                    logger.error("存在非法数据：" + HexBytesUtil.bytesToHex(bytes));
                }

            }
        }
    }
}
